package com.smarthome.common.exception;

import com.smarthome.domain.enums.ResponseCode;

public class BaseException extends AppException {

    private static final long serialVersionUID = 1L;
    // 所属模块
    private String module;
    // 错误码
    private ResponseCode exceptionType;
    private String code;
    // 错误码对应的参数
    private Object[] args;
    // 默认错误消息
    private String defaultMessage;

    public BaseException(String module, ResponseCode exceptionType, String defaultMessage, Object... args) {
        this.module = module;
        this.exceptionType = exceptionType;
        this.code = exceptionType != null ? exceptionType.getCode() : "";
        this.args = args;
        this.defaultMessage = defaultMessage;
    }

    public BaseException(String module, ResponseCode exceptionType, Object... args) {
        this(module, exceptionType, null, args);
    }

    public BaseException(ResponseCode exceptionType, Object... args) {
        this(null, exceptionType, null, args);
    }

    public BaseException(String code, Object... args) {
        this(null, ResponseCode.get(code), null, new Object[] {});
    }

    public BaseException(ResponseCode exceptionType) {
        this(null, exceptionType, null, new Object[] {});
    }

    @Override
    public String getMessage() {
        // 资源文件中读取错误信息
        String message = null;
        if (exceptionType != null) {
            message = exceptionType.getMessage(args);
        }
        if (message == null) {
            message = defaultMessage;
        }
        return message;
    }

    @Override
    public String toString() {
        return this.getClass() + "{" + "module='" + module + '\'' + ", message='" + getMessage() + '\'' + '}';
    }

    public String getCode() {
        return code;
    }

}
